//
//  UITextView + Extension.swift
//  Weibo - Swift
//
//  Created by user on 16/5/2.
//  Copyright © 2016年 user. All rights reserved.
//

import UIKit

extension UITextView{
    
    var emoticonText:String?{
        
        var result = ""
        
        let attr = self.attributedText
        
        attr.enumerateAttributesInRange(NSMakeRange(0, attr.length), options: []) { (dict, range, _) -> Void in
            
            if let attch = dict["NSAttachment"] as? FANTextAttachment {
                
                result += attch.emoticon?.chs ?? ""
            }else{
                
                result += (attr.string as NSString).substringWithRange(range)
            }
            
            
        }
        
        return result
    }
    
        func insertEmoticon(emoticon:FANEmoticon){
        
        let originalAttr = NSMutableAttributedString(attributedString: self.attributedText)
        
        let image = UIImage(named: "\(emoticon.folderName ?? "")/\(emoticon.png ?? "")", inBundle: FANEmoticonViewModel.sharedEmoticon.emoticonBundle, compatibleWithTraitCollection: nil)
        
        let attchment = FANTextAttachment()
        
        attchment.emoticon = emoticon
        
        attchment.image = image
        
        attchment.bounds = CGRectMake(0, -4, self.font!.lineHeight, self.font!.lineHeight)
        
        let att = NSAttributedString(attachment: attchment)
        
        var selectedRange = self.selectedRange
        
        originalAttr.replaceCharactersInRange(selectedRange, withAttributedString: att)
            
        originalAttr.addAttribute(NSFontAttributeName, value: self.font!, range: NSMakeRange(0, originalAttr.length))
            
        self.attributedText = originalAttr
        
        selectedRange.location += 1
        
        selectedRange.length = 0
        
        self.selectedRange = selectedRange
            
        NSNotificationCenter.defaultCenter().postNotificationName(UITextViewTextDidChangeNotification, object: nil)
            
        delegate?.textViewDidChange!(self)
        
    }
    
    
}
